import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store/index'
import { getTimeStamp } from '@/utils/auth'
import router from '@/router'
// 创建一个axios的实例
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 5000
})
// 请求拦截器
service.interceptors.request.use(config => {
    if (store.getters.token) {
        if (isChecktTimeOut()) {
            store.commit('user/logout') // 登出action 删除token
            router.push('/login')
            return Promise.reject(new Error('token超时了'))
        }
        config.headers.Authorization = "Bearer " + store.getters.token
    }
    return config
}, error => {
    return Promise.reject(error)
})
// 响应拦截器
service.interceptors.response.use(response => {
    const { success, message, data } = response.data
    if (success) {
        return data
    } else {
        Message.error(message)
        return Promise.reject(new Error(message))
    }
}, error => {
    if (error.response && error.response.data && error.response.data.code === 10002) {
        // 当等于10002的时候 表示 后端告诉我token超时了
        store.commit('user/logout') // 登出action 删除token
        router.push('/login')
    }
    Message.error(error.message)
    return Promise.reject(error)
})
export default service // 导出axios实例
function isChecktTimeOut() {
    const nowtime = +new Date()
    return (nowtime - getTimeStamp()) / 1000 > 3600
}